package com.youbug.kefu.interceptor;

import com.youbug.kefu.exception.NoLoginException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();
        System.out.println(requestURI);

        List<String> permission = (List<String>)request.getSession().getAttribute("permission");
        List<String> loginAccess = Arrays.asList("common","useDic");// 登录后可以访问的controller
        if("/login".equals(requestURI)
                || requestURI.startsWith("/client")//客户端页面请求不拦截
                || requestURI.startsWith("/keepalive")//保持会话的请求不拦截
                ){//使用字典的请求不拦截
            return true;
        }else{
            if(permission == null){
                throw new NoLoginException("登录超时或未登录，请重新登录");
            }else{
                if(permission.contains(requestURI.split("/")[1])){
                    return true;
                }else{
                    if(loginAccess.contains(requestURI.split("/")[1])){
                        return true;
                    }
                    throw  new RuntimeException("缺少访问权限");
                }
            }
        }
    }
}
